package org.dromara.system.dict.spi;

import org.dromara.common.core.exception.ServiceException;
import org.dromara.system.dict.domain.Dictionary;
import org.dromara.system.dict.domain.Select;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 扩展服务类
 */
public interface SpiService {

    /**
     * 查询所有的数据字典
     *
     * @return Map<String, Map < String, String>>
     */
    Map<String, Map<String, String>> dictionaries();

    /**
     * 查询 字典的 map
     *
     * @return Map<字典code, 字典名称>
     */
    default Map<String, String> toMap() {
        throw new ServiceException("请重写获取字典map的方法");
    }

    /**
     * 将list转成map
     *
     * @param lists lists
     * @return map
     */
    default <T extends Dictionary> Map<String, String> toMap(List<T> lists) {
        if (CollectionUtils.isEmpty(lists)) {
            return Collections.emptyMap();
        }
        return lists.stream()
            .sorted(Comparator.comparing(e->{
                Integer sort = e.getSortId();
                if (Objects.isNull(sort)){
                    return 0;
                }
                return e.getSortId();
            }))
            .collect(Collectors.toMap(Dictionary::getCode, Dictionary::getName,(x1, x2)->x2, LinkedHashMap::new));
    }


    /**
     * 查询 字典的 下拉
     *
     * @return List<Select < String>>
     */
    default List<Select<String>> toSelect() {
        throw new ServiceException("请重写获取字典下拉的方法");
    }

    /**
     * 将 list 转成 Select
     *
     * @param lists lists
     * @return List<Select < String>>
     */
    default <T extends Dictionary> List<Select<String>> toSelect(List<T> lists) {
        if (CollectionUtils.isEmpty(lists)) {
            return Collections.emptyList();
        }
        return lists.stream()
            .peek(e -> {
                if (Objects.isNull(e.getSortId())) {
                    e.setSortId(0);
                }
            })
            .sorted(Comparator.comparing(Dictionary::getSortId))
            .map(e -> new Select<>(e.getName(), e.getCode()))
            .collect(Collectors.toList());
    }
}
